package org.luxor.cloud.gateway.component.security;

import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.luxor.cloud.gateway.component.Jackson2Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 403 匿名用户(未登陆),无权访问受限资源响应处理器
 *
 * @author yanxinming @date 2020/06/03
 */
public class HttpOAuth2ServerAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    private static final Logger log = LoggerFactory.getLogger(HttpOAuth2ServerAuthenticationEntryPoint.class);

    @SneakyThrows
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String remoteAddress = request.getRemoteAddress().getHostString();
        String requestPath = request.getURI().getPath();
        log.debug("当前来源IP:[{}] 禁止访问:[{}]", remoteAddress, requestPath);

        Map<String, Object> unauthorizedError = new HashMap<>(5);
        unauthorizedError.put("code", HttpStatus.UNAUTHORIZED.value());
        unauthorizedError.put("message", "未授权访问");
        unauthorizedError.put("data", StringUtils.EMPTY);
        String jsonBody = Jackson2Mapper.toJson(unauthorizedError);

        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        DataBuffer buffer = response.bufferFactory().wrap(jsonBody.getBytes(Charset.forName("UTF-8")));
        return response.writeWith((Mono.just(buffer)));
    }
}
